package com.wchat.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Activity;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;

public class Util {
	
	private static int SIZE_IMAGE_MESSAGE = 72;
	
	public static String getUriFilePath(Activity context, Uri uri) {
		String scheme = uri.getScheme();
		if ("file".equalsIgnoreCase(scheme)) {
			return uri.getPath();
		} else if ("content".equalsIgnoreCase(scheme)) {
			String[] proj = { MediaStore.Images.Media.DATA };
	        Cursor cursor = context.managedQuery(uri, proj, null, null, null);
	        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	        cursor.moveToFirst();
	        return cursor.getString(column_index);
		}
		return "";
	}
	
	public static Bitmap getScaleBitmap(String path)
	{
		if(path == null) return null;
		
		File file = new File(path);
		
		if(!file.exists()) return null;
		
		FileInputStream fis  =null;
		byte[] buffer = null;
		try {
			fis = new FileInputStream(file);
			try {
				buffer = new byte[(int)file.length()];
				fis.read(buffer);
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		if(buffer == null) return null;
		
		Bitmap oBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
		
		if(oBitmap == null) return null;
		//thumbnail size is 48*48
		Bitmap thumbnail = Bitmap.createScaledBitmap(oBitmap, SIZE_IMAGE_MESSAGE, SIZE_IMAGE_MESSAGE, false);
		oBitmap.recycle();
		oBitmap = null;
		System.gc();
		System.gc();
		
		return thumbnail;
	}
	
	public static Bitmap getScaleBitmap(File file)
	{

		if(!file.exists()) return null;
		
		FileInputStream fis  =null;
		byte[] buffer = null;
		try {
			fis = new FileInputStream(file);
			try {
				buffer = new byte[(int)file.length()];
				fis.read(buffer);
				fis.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}

		if(buffer == null) return null;
		
		Bitmap oBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
		
		if(oBitmap == null) return null;
		//thumbnail size is 48*48
		Bitmap thumbnail = Bitmap.createScaledBitmap(oBitmap, SIZE_IMAGE_MESSAGE, SIZE_IMAGE_MESSAGE, false);
		oBitmap.recycle();
		oBitmap = null;
		System.gc();
		System.gc();
		
		return thumbnail;
	}


}
